package com.yindian.cos.easy.security.authentication.login.social.weibo;

import com.yindian.cos.easy.security.authentication.login.social.core.AbstractSocialAuthentication;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.WeiBoProperties;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微博登录拦截器
 *
 * @author zhangchuanhao
 * @create 2018/11/19
 */
@Log4j2
public class WeiBoLoginAuthentication extends AbstractSocialAuthentication {

    private final WeiBoProperties weiBoProperties;

    private final String loginUrl;

    private final String method;

    public WeiBoLoginAuthentication(EasySecurityProperties easySecurityProperties) {
        this.weiBoProperties = easySecurityProperties.getWeibo();
        this.loginUrl = weiBoProperties.getLoginUrl();
        this.method = weiBoProperties.getMethod();
    }

    @Override
    public boolean support(HttpServletRequest request) {
        return support(request, method, loginUrl);
    }

    @Override
    public int order() {
        return weiBoProperties.getOrder();
    }

    @Override
    public void redirectAuthorization(HttpServletResponse response) throws IOException {
        String url = weiBoProperties.getAuthorizationCodeUrl();
        url += "?client_id=" + weiBoProperties.getAppKey();
        url += "&redirect_uri=" + weiBoProperties.getDomain() + weiBoProperties.getRedirectUri();
        if (StringUtils.isNotBlank(weiBoProperties.getScope())) {
            url += "&scope=" + weiBoProperties.getScope();
        }
        if (StringUtils.isNotBlank(weiBoProperties.getState())) {
            url += "&state=" + weiBoProperties.getState();
        }
        if (StringUtils.isNotBlank(weiBoProperties.getDisplay())) {
            url += "&display=" + weiBoProperties.getDisplay();
        }
        url += "&forcelogin=" + weiBoProperties.getForcelogin();
        if (StringUtils.isNotBlank(weiBoProperties.getLanguage())) {
            url += "&language=" + weiBoProperties.getLanguage();
        }
        response.sendRedirect(url);
        log.debug(ProviderName.WEIBO + "登录引导用户跳转至授权页面...");
    }
}
